package com.cj.pj.sys.common.aspect;

import com.cj.pj.sys.common.annotation.AddLogs;
import com.cj.pj.sys.pojo.SysLog;
import com.cj.pj.sys.service.SysLogService;
import com.cj.pj.sys.util.IPUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Aspect
@Component
public class SysLogAspect {
    @Autowired
    SysLogService sysLogService;

    @Pointcut("@annotation(com.cj.pj.sys.common.annotation.AddLogs)")
    public void addLog(){};

    @Around("addLog()")
    public Object advice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Date createdTime=new Date();
        SysLog sysLog=new SysLog();
        Object[] args=proceedingJoinPoint.getArgs();
        MethodSignature methodSignature= (MethodSignature) proceedingJoinPoint.getSignature();
        String[] argsNmae=methodSignature.getParameterNames();
        Method method=proceedingJoinPoint.getTarget().getClass().getDeclaredMethod(methodSignature.getName(),methodSignature.getParameterTypes());
        String operation= method.getDeclaredAnnotation(AddLogs.class).value();
        Map<String,Object> argsMap=new HashMap<>();
        for(int i=0;i<args.length;i++){
            argsMap.put(argsNmae[i],args[i]);
        }


        Long startTime=System.currentTimeMillis();
        Object result=proceedingJoinPoint.proceed();
        Long endTime=System.currentTimeMillis();

        sysLog.setUsername("tset1");
        sysLog.setOperation(operation);
        sysLog.setTime(endTime-startTime);
        sysLog.setParams(argsMap.toString());
        sysLog.setMethod(proceedingJoinPoint.getTarget().getClass().getName()+"."+method.getName());
        sysLog.setIp(IPUtils.getIpAddr());
        sysLog.setCreatedTime(createdTime);
        sysLogService.insert(sysLog);
        return result;
    }
}
